﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI.WebControls;

using HelfenHelfen.Web.Forms.Site.Utility;

namespace HelfenHelfen.Web.Forms.Site {
   public partial class Register : System.Web.UI.Page {
      protected global::System.Web.UI.WebControls.CreateUserWizard RegisterUser;

      protected void CreateUserWizard1_CreatingUserError(object sender, CreateUserErrorEventArgs e) {
         string msg = GetErrorMessage(e.CreateUserError);
      }


      public string GetErrorMessage(MembershipCreateStatus status) {
         switch (status) {
            case MembershipCreateStatus.DuplicateUserName:
               return "Username already exists. Please enter a different user name.";

            case MembershipCreateStatus.DuplicateEmail:
               return "A username for that e-mail address already exists. Please enter a different e-mail address.";

            case MembershipCreateStatus.InvalidPassword:
               return "The password provided is invalid. Please enter a valid password value.";

            case MembershipCreateStatus.InvalidEmail:
               return "The e-mail address provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidAnswer:
               return "The password retrieval answer provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidQuestion:
               return "The password retrieval question provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.InvalidUserName:
               return "The user name provided is invalid. Please check the value and try again.";

            case MembershipCreateStatus.ProviderError:
               return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            case MembershipCreateStatus.UserRejected:
               return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

            default:
               return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
         }
      }
      

      protected void CreateUserWizard1_FinishButtonClick(object sender, EventArgs e) {
         // Create an empty Profile for the newly created user
         HttpContext.Current.Profile.SetPropertyValue("FirstName", ((TextBox)this.FindControlRecursive("txtFirstName")).Text);
         HttpContext.Current.Profile.SetPropertyValue("LastName", ((TextBox)this.FindControlRecursive("txtLastName")).Text);
         HttpContext.Current.Profile.SetPropertyValue("Street", ((TextBox)this.FindControlRecursive("txtStreet")).Text);
         HttpContext.Current.Profile.SetPropertyValue("PostalCode", ((TextBox)this.FindControlRecursive("txtZip")).Text);
         HttpContext.Current.Profile.SetPropertyValue("City", ((TextBox)this.FindControlRecursive("txtCity")).Text);
         HttpContext.Current.Profile.SetPropertyValue("CountryCode", ((TextBox)this.FindControlRecursive("txtCountry")).Text);
         HttpContext.Current.Profile.SetPropertyValue("EMail", ((TextBox)this.FindControlRecursive("Email")).Text);
         HttpContext.Current.Profile.SetPropertyValue("PhoneNo", ((TextBox)this.FindControlRecursive("txtPhone")).Text);
      }


      //TODO: change upload mechanism
      protected void RegisterUser_CreatedUser(object sender, EventArgs e) {
         // http://forums.devshed.com/net-development-87/storing-custom-field-data-from-createuserwizard-step-within-oncreateduser-event-657224.html        
         FormsAuthentication.SetAuthCookie(RegisterUser.UserName, false /* createPersistentCookie */);

      //System.Web.Profile.ProfileBase.Create(RegisterUser.UserName, true);

      bool test = HttpContext.Current.Profile.IsAnonymous;

         
       //  UserProfile profile = (UserProfile) UserProfile.Create(RegisterUser.UserName, true);
      //   HttpContext.Current.Profile.SetPropertyValue("ProfileTest", "+436641927156");
         // Profile.Phone = "Test";


         SqlConnection connection = null;
         try {
            FileUpload img = (FileUpload) RegisterUser.FindControlRecursive("ctlPicture");
            Byte[] imgByte = null;
            if (img.HasFile && img.PostedFile != null) {
               //To create a PostedFile
               HttpPostedFile File = img.PostedFile;
               //Create byte Array with file len
               imgByte = new Byte[File.ContentLength];
               //force the control to load data in array
               File.InputStream.Read(imgByte, 0, File.ContentLength);
            }
            // Insert the employee name and image into db
            // string conn = ConfigurationManager.ConnectionStrings ["EmployeeConnString"].ConnectionString;
            string conn = @"Data Source=ASCHABUS1;Initial Catalog=HelfenHelfen;Integrated Security=True";
            connection = new SqlConnection(conn);

            connection.Open();
            // string sql = "INSERT INTO EmpDetails(empname,empimg) VALUES(@enm, @eimg) SELECT @@IDENTITY";
            string sql = "INSERT INTO Image(Title, ImageData, CreatorID) VALUES(@enm, @eimg, @user ) SELECT @@IDENTITY";
            SqlCommand cmd = new SqlCommand(sql, connection);
            cmd.Parameters.AddWithValue("@enm", "Testimage" /* txtEName.Text.Trim() */);
            cmd.Parameters.AddWithValue("@eimg", imgByte);
            cmd.Parameters.AddWithValue("@user", 123);
            int id = Convert.ToInt32(cmd.ExecuteScalar());
            // lblResult.Text = String.Format("Employee ID is {0}", id);
            string result = String.Format("Employee ID is {0}", id);
         } catch (Exception ex) {
            // lblResult.Text = "There was an error";
         } finally {
            connection.Close();
         }
      }
   }
}